<?php

namespace App\Service;

use App\Model\Order;
use App\Model\OrderGood;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Psr\Http\Message\ResponseInterface;

class OrderService extends BaseService
{


    /**
     *
     * @return void
     */
    public function preOrder()
    {

    }


    public function createOrder($params)
    {


    }


    /**
     * 创建订单预支付
     * @param $orderId
     * @return ResponseInterface
     */
    public function paymentIntent($orderId)
    {


        $orderInfo = Order::find($orderId);
        if (is_null($orderInfo) || $orderInfo['status'] != 0) {
            return $this->response->returnFail();
        }


        switch ($orderInfo['pay_method']) {
            case 1:
                //微信
                $payInfo = null;
                break;
            case 2:
                //支付宝
                $payInfo = null;
                break;
            case 3:
        }


        return $this->response->returnSuccess(['payInfo' => null, 'price' => $orderInfo['price'], 'orderNo' => $orderInfo['order_no']]);


    }

    public function confirmOrder($orderNo)
    {

        $orderInfo = Order::where(['order_no'=>$orderNo])->first();

        $this->completeOrder($orderNo);

        $orderGoods = OrderGood::where(['uid'=>$orderInfo['uid'],'order_id'=>$orderInfo['id']])->select(['status','aid as uid','pre_start_time as start','pre_end_time as end'])->first();



        if ($orderGoods){
            $orderGoods = $orderGoods->toArray();
        }

        return ['code' => 1,'orderGoods'=>$orderGoods];

    }

    /**
     * 完成订单
     * @return bool
     */
    public function completeOrder($orderNo)
    {

        $orderInfo = Order::where(['order_no'=>$orderNo])->first();
        if (is_null($orderInfo)) {
            return false;
        }
        $orderInfo = $orderInfo->toArray();


        Db::beginTransaction();
        try {

            // 生成商品订单
            $rel = OrderGood::addOrderGoods($orderInfo);

            if (!$rel) {
                Db::rollBack();
                return false;
            }
            $data = [
                'pay_status' => 1,
                'status' => 1,
                'update_time'=>time(),
                'pay_time'=>time()
            ];

            Order::where(['order_no' => $orderNo])->update($data);

            Db::commit();
            return true;

        } catch (\Exception $e) {

            Db::rollBack();
            recordExceptionLog('定确认失败',$e->getMessage());
            return false;

        }


    }


}
